<template>
  <!--超管后台-->
  <div class="rr-login" v-if="domain && (domain.indexOf('console.noctech.cn')>=0 || domain.indexOf('console.nocexpo.com')>=0)" :style="{ backgroundImage: `url(${backgroundImage})` }">
    <div class="rr-login-wrap">
      <div class="rr-login-left hidden-sm-and-down"></div>
      <div class="rr-login-right">
        <div class="rr-login-right-main">
          <div style="display: flex;">
            <img src="../assets/images/logo2.png" alt="" style="width: 63px;height: 51px;margin-top: 20px;">
            <h4 class="rr-login-right-main-title" style="color: rgba(0, 0, 0, 1);font-size: 24px;font-weight: 600;">
                金诺云展管理后台
            </h4>
          </div>
<!--          <el-form ref="formRef" label-width="80px" :status-icon="true" :model="login" :rules="rules"-->
<!--                   @keyup.enter="onLogin">-->
<!--            -->
<!--            -->
<!--            <el-form-item label-width="0" prop="username">-->
<!--              <el-input v-model="login.username" :placeholder="$t('ui.login.userNamePlaceholder')" prefix-icon="user"-->
<!--                        autocomplete="off" style="width: 441px;height: 50px;border-radius: 12px 12px 12px 12px;"></el-input>-->
<!--            </el-form-item>-->
<!--            <el-form-item label-width="0" prop="password">-->
<!--              <el-input :placeholder="$t('ui.login.passwordPlaceholder')" v-model="login.password" prefix-icon="lock"-->
<!--                        autocomplete="off" show-password style="width: 441px;height: 50px;"></el-input>-->
<!--            </el-form-item>-->
<!--            <el-form-item label-width="15" style="margin-top: -10px;">-->
<!--              <el-checkbox  label="Option 1" size="large" >记住密码</el-checkbox>-->
<!--            </el-form-item>-->
<!--            &lt;!&ndash;-->
<!--            <el-form-item label-width="0" prop="captcha">-->
<!--              <el-space class="rr-login-right-main-code">-->
<!--                <el-input v-model="login.captcha" :placeholder="$t('ui.login.captchaPlaceholder')"-->
<!--                  prefix-icon="first-aid-kit" style="height: 50px"></el-input>-->
<!--                <img style="vertical-align: middle; height: 40px; cursor: pointer" :src="state.captchaUrl"-->
<!--                  @click="onRefreshCode" alt="" />-->
<!--              </el-space>-->
<!--            </el-form-item>-->
<!--            &ndash;&gt;-->
<!--            <el-form-item label-width="0" style="margin-top: -20px;">-->
<!--              <el-button  size="small" :disabled="state.loading" @click="onVerify" style="background: linear-gradient(109.28deg, rgba(9, 173, 249, 1) 0%, rgba(70, 80, 251, 1) 100%);-->
<!--box-shadow: 0px 0px 10px  rgba(18, 160, 249, 0.88); width: 327px;height: 53.47px;color: #fff;border-radius: 8px;"-->
<!--                          class="rr-login-right-main-btn" >-->
<!--                {{ $t("ui.login.loginBtn") }}-->
<!--              </el-button>-->
<!--            </el-form-item>-->
<!--          </el-form>-->

          <el-form ref="formRef" label-width="80px" :status-icon="true" :model="login" :rules="rules"
                   @keyup.enter="onLogin">
            <el-form-item label-width="0" prop="username">
              <el-input v-model="login.username" :placeholder="$t('ui.login.userNamePlaceholder')" prefix-icon="user"
                        autocomplete="off" style="width: 441px;height: 50px;border-radius: 12px 12px 12px 12px;"></el-input>
            </el-form-item>
            <el-form-item label-width="0" prop="password" v-if="login.loginType == 2">
              <el-input :placeholder="$t('ui.login.passwordPlaceholder')" v-model="login.password" prefix-icon="lock"
                        autocomplete="off" show-password style="width: 441px;height: 50px;"></el-input>
            </el-form-item>
            <el-form-item label-width="0" prop="phone" v-if="login.loginType == 1">
              <el-input v-model="login.phone" :placeholder="$t('ui.login.phonePlaceholder')" prefix-icon="phone"
                        autocomplete="off" style="width: 441px;height: 50px;border-radius: 12px 12px 12px 12px;"></el-input>
            </el-form-item>
            <el-form-item label-width="0" prop="captcha" v-if="login.loginType == 1">
              <el-space class="rr-login-right-main-code">
                <el-input v-model="login.phoneVerCode" placeholder="验证码"
                          prefix-icon="first-aid-kit" style="height: 50px"></el-input>
                <el-button
                  :disabled="state.countdown > 0"
                  @click="getCheckCode"
                  style="width: 120px; height: 40px;"
                >
                  {{ state.countdown > 0 ? `${state.countdown}秒后重试` : '获取验证码' }}
                </el-button>
              </el-space>
            </el-form-item>

            <el-form-item label-width="15" style="margin-top: -10px;" v-if="login.loginType == 2">
              <el-checkbox  label="Option 1" size="large" >记住密码</el-checkbox>
            </el-form-item>

            <el-form-item label-width="0" style="margin-top: -20px;">
              <el-button  size="small" :disabled="state.loading" @click="onVerify" style="background: linear-gradient(109.28deg, rgba(9, 173, 249, 1) 0%, rgba(70, 80, 251, 1) 100%);
box-shadow: 0px 0px 10px  rgba(18, 160, 249, 0.88); width: 327px;height: 53.47px;color: #fff;border-radius: 8px;"
                          class="rr-login-right-main-btn" >
                {{ $t("ui.login.loginBtn") }}
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
  <!--商家后台-->
  <div class="rr-login" v-else  :style="{ backgroundImage: `url(${backgroundImage})` }">
    <div class="rr-login-wrap">
      <div class="rr-login-left hidden-sm-and-down"></div>
      <div class="rr-login-right">
        <div class="rr-login-right-main">
          <div style="display: flex;">
            <img src="../assets/images/logo2.png" alt="" style="width: 63px;height: 51px;margin-top: 20px;">
            <h4 class="rr-login-right-main-title" style="color: rgba(0, 0, 0, 1);font-size: 24px;font-weight: 600;">
                金诺云展商家后台
            </h4>
          </div>
          <!-- 登录方式切换 -->
          <div class="login-method-tabs">
            <el-radio-group v-model="login.loginType" @change="changeLoginMethod">
              <el-radio-button label="2">密码登录</el-radio-button>
              <el-radio-button label="1">验证码登录</el-radio-button>
            </el-radio-group>
          </div>

          <el-form ref="formRef" label-width="80px" :status-icon="true" :model="login" :rules="rules"
                   @keyup.enter="onLogin">
            <el-form-item label-width="0" prop="username">
              <el-input v-model="login.username" :placeholder="$t('ui.login.userNamePlaceholder')" prefix-icon="user"
                        autocomplete="off" style="width: 441px;height: 50px;border-radius: 12px 12px 12px 12px;"></el-input>
            </el-form-item>
            <el-form-item label-width="0" prop="password" v-if="login.loginType == 2">
              <el-input :placeholder="$t('ui.login.passwordPlaceholder')" v-model="login.password" prefix-icon="lock"
                        autocomplete="off" show-password style="width: 441px;height: 50px;"></el-input>
            </el-form-item>
            <el-form-item label-width="0" prop="captcha" v-if="login.loginType == 1">
              <el-space class="rr-login-right-main-code">
                <el-input v-model="login.phoneVerCode" placeholder="验证码"
                          prefix-icon="first-aid-kit" style="height: 50px"></el-input>
                <el-button
                  :disabled="state.countdown > 0"
                  @click="getCheckCode"
                  style="width: 120px; height: 40px;"
                >
                  {{ state.countdown > 0 ? `${state.countdown}秒后重试` : '获取验证码' }}
                </el-button>
              </el-space>
            </el-form-item>

            <el-form-item label-width="15" style="margin-top: -10px;" v-if="login.loginType == 2">
              <el-checkbox  label="Option 1" size="large" >记住密码</el-checkbox>
            </el-form-item>

            <el-form-item label-width="0" style="margin-top: -20px;">
              <el-button  size="small" :disabled="state.loading" @click="onVerify" style="background: linear-gradient(109.28deg, rgba(9, 173, 249, 1) 0%, rgba(70, 80, 251, 1) 100%);
box-shadow: 0px 0px 10px  rgba(18, 160, 249, 0.88); width: 327px;height: 53.47px;color: #fff;border-radius: 8px;"
                          class="rr-login-right-main-btn" >
                {{ $t("ui.login.loginBtn") }}
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted,onBeforeUnmount, reactive, ref } from "vue";
import { CacheToken } from "@/constants/cacheKey";
import Lang from "@/components/base/lang/index";
import baseService from "@/service/baseService";
import { setCache } from "@/utils/cache";
import { ElMessage } from "element-plus";
import { getUuid } from "@/utils/utils";
import app from "@/constants/app";
import backgroundImage from '@/assets/images/background-image.png';
import SvgIcon from "@/components/base/svg-icon/index";
import { useAppStore } from "@/store";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { sliderVerification, ApplySlider } from "@/utils/sliderValidator"

const store = useAppStore();
const router = useRouter();
const { t } = useI18n();
declare const TencentCaptcha: any;

const state = reactive({
  captchaUrl: "",
  loading: false,
  year: new Date().getFullYear(),
  countdown: 0,
  timer: null as any
});

const login = reactive(
  {
    username: "",
    password: "",
    phoneVerCode: "",
    uuid: "",
    type: 0,
    randstr: "",
    ticket: '',
    loginType: 2  //1验证码登录 2密码登录
  }
);

//滑块验证器
let applySlider: ApplySlider

onMounted(() => {
  getDomain();
  //清理数据
  store.logout();
  getCaptchaUrl();
  //autoLogin();
  //初始化滑块验证器
  applySlider = sliderVerification();
  sessionStorage.removeItem('AUTH_TIP_SHOWN'); // ★ 先清，保证登录前一定不标记
});
const formRef = ref();

const rules = ref({
  username: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  password: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  //captcha: [{ required: true, message: t("validate.required"), trigger: "blur" }]
});

// 开始验证
async function onVerify() {
  const res = await applySlider()
  console.log('SliderValidatorResult:', res)
  if (res.ret === 0) {
    //login.phoneVerCode = res.ticket;
    login.randstr = res.randstr;
    onLogin();
  }
};

const getCaptchaUrl = () => {
  login.uuid = getUuid();
  state.captchaUrl = `${app.api}/captcha?uuid=${login.uuid}`;
};

const onRefreshCode = () => {
  getCaptchaUrl();
};

const onLogin = () => {
  //loginType  1验证码登录 2密码登录

  formRef.value.validate((valid: boolean) => {
    if (valid) {
      state.loading = true;
      if (login.loginType == 1){
        loginByAuthCode();
        return;
      }
      baseService
        .post("/sys/login", login)
        .then((res) => {
          state.loading = false;
          if (res.code === 0) {
            setCache(CacheToken, res.data, true);
            //把账号密码写入到localStorage
            localStorage.setItem("username", login.username);
            localStorage.setItem("password", login.password);
            ElMessage.success(t("ui.login.loginOk"));
            router.push("/");
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {
          state.loading = false;
          onRefreshCode();
        });
    }
  });
};

/**
 * 自动登录
 */
const autoLogin = () => {
  console.log("auto=1");
  //获取页面传的参数username
  const tk = router.currentRoute.value.query.tk + '';
  if(!tk){
    return;
  }
  const params = tk.split('uap');
  if(params.length != 2){
    return;
  }
  //把账号密码写入到localStorage
  const username = window.atob(params[0]);
  const password = window.atob(params[1]);
  if (username && password) {
    login.username = username;
    login.password = password;
    login.type = 1; //自动登录
    onLogin();
  }
};

//获取域名
const domain = ref();
const getDomain = () => {
  domain.value = window.location.host;
  console.log(domain.value)
}

// 获取验证码方法
const getCheckCode = () => {
  if (!login.username) {
    ElMessage.warning('请输入手机号或邮箱');
    return;
  }
  baseService.get("sys/user/ifNocUserExistByPhone", {
    username: login.username
  }).then(res => {
    if (res.code === 0) {
      let captcha =  new TencentCaptcha("194163642", (res:any)=>{
        if (res.ret === 0) {
          startCountdown();
          baseService.post(`/h5/testDescribeCaptchaResult`,{
            randstr: res.randstr,
            ticket: res.ticket,
            phone:login.username,
          }).then(res=>{
            if (res.code == 0 && res.CaptchaCode == 1){
              ElMessage.success("发送验证码成功")
            }else{
              ElMessage.error("验证失败")
            }
          })
        }
      });
      captcha.show();
    } else {
      ElMessage.error(res.msg || '验证码发送失败');
    }
  }).catch(err => {
    ElMessage.error('验证码发送失败');
  });
};
function loginByAuthCode() {
  if (!login.username) {
    ElMessage.error("请输入手机号");
    return;
  }
  if (!login.phoneVerCode) {
    ElMessage.error("请输入手机验证码");
    return;
  }
  state.loading = true;
  // loginType=1验证码登录
  baseService.post("sys/login", {
    username: login.username,
    phoneVerCode: login.phoneVerCode,
    // captcha: login.captcha,
    loginType: 1
  }).then(res => {
    state.loading = false;
    if (res.code === 0) {
      setCache(CacheToken, res.data, true);
      //把账号密码写入到localStorage
      localStorage.setItem("username", login.username);
      localStorage.setItem("password", login.password);
      ElMessage.success(t("ui.login.loginOk"));
      router.push("/");
    } else {
      ElMessage.error(res.msg);
    }
  }) .catch(() => {
    ElMessage.error("登录失败");
  })
    .finally(() => {
      state.loading = false;
    });
};
// 开始倒计时
const startCountdown = () => {
  state.countdown = 60;
  state.timer = setInterval(() => {
    state.countdown--;
    if (state.countdown <= 0 && state.timer) {
      clearInterval(state.timer);
      state.timer = null;
    }
  }, 1000);
};

// 组件卸载时清除定时器
onBeforeUnmount(() => {
  if (state.timer) {
    clearInterval(state.timer);
    state.timer = null;
  }
});


// 切换登录方式
const changeLoginMethod = () => {
  login.password = '';
  login.phoneVerCode = '';
};



</script>

<style lang="less" scoped>
::v-deep .el-input__prefix{
  font-size: 22px !important;
}

::v-deep .el-input__wrapper{
  box-shadow:none;
  border-bottom: 1px solid rgba(211, 218, 230, 1);

}
@import url("@/assets/theme/base.less");
.rr-login {
  width: 100vw;
  height: 100vh;
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  @media only screen and (max-width: 992px) {
    .rr-login-wrap {
      width: 96% !important;
    }
    .rr-login-right {
      width: 100% !important;
    }
  }

  &-wrap {
    margin: 0 auto;
    width: 1000px;
    animation-duration: 1s;
    animation-fill-mode: both;
    border-radius: 5px;
    overflow: hidden;
    position: absolute;
    top: 25%;
    right: 23%;

  }
  &-left {
    justify-content: center;
    flex-direction: column;
    color: #fff;
    float: left;
    width: 50%;

    &-title {
      text-align: center;
      color: #fff;
      font-weight: 300;
      letter-spacing: 2px;
      font-size: 32px;
    }
  }

  &-right {
    border-left: none;
    color: #fff;
    width: 50%;
    float: left;

    &-main {
      margin: 0 auto;
      width: 65%;
      &-title {
        color: #333;
        margin-bottom: 40px;
        font-weight: 500;
        font-size: 24px;
        text-align: center;
        letter-spacing: 4px;
      }

      &-lang .iconfont {
        font-size: 20px;
        color: #606266;
        font-weight: 800;
        width: 20px;
        height: 20px;
      }



      .el-input__inner {
        border-width: 0;
        border-radius: 0;
        border-bottom: 1px solid #dcdfe6;
        box-shadow:none !important;
      }


      &-code {
        width: 100%;
        .el-space__item:first-child {
          flex: 1;
        }
      }
      &-btn {
        width: 100%;
        height: 45px;
        font-size: 18px !important;
        letter-spacing: 2px;
        font-weight: 300 !important;
        cursor: pointer;
        margin-top: 30px;
        font-family: neo, sans-serif;
        transition: 0.25s;
      }
    }
  }

  .login-footer {
    text-align: center;
    position: absolute;
    bottom: 0;
    padding: 20px;
    color: rgba(255, 255, 255, 0.6);
    p {
      margin: 10px 0;
    }
    a {
      padding: 0 5px;
      color: rgba(255, 255, 255, 0.6);
      &:focus,
      &:hover {
        color: #fff;
      }
    }
  }

  &-left,
  &-right {
    position: relative;
    min-height: 500px;
    align-items: center;
    display: flex;
  }

  @keyframes animate-down {

    0%,
    60%,
    75%,
    90%,
    to {
      animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
    }

    0% {
      opacity: 0;
      transform: translate3d(0, -3000px, 0);
    }

    60% {
      opacity: 1;
      transform: translate3d(0, 25px, 0);
    }

    75% {
      transform: translate3d(0, -10px, 0);
    }

    90% {
      transform: translate3d(0, 5px, 0);
    }

    to {
      transform: none;
    }
  }

  .animate-down {
    animation-name: animate-down;
  }

  // 在style部分添加
  .login-method-tabs {
    margin-bottom: 20px;
    text-align: center;

    .el-radio-group {
      width: 100%;

      .el-radio-button {
        width: 50%;

        :deep(.el-radio-button__inner) {
          width: 100%;
        }
      }
    }
  }

}

</style>
